package com.greenhouse.business.common.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * @版权 : Copyright (c) 2020 儒安物联技术研发中心
 * @author: 雷扬
 * @E-mail: leiyang@runaiot.com
 * @版本: 1.0
 * @创建日期: 2021年5月8日 下午4:31:46
 * @ClassName WarningWebsocket
 * @类描述-Description: TODO(这里用一句话描述这个方法的作用)
 * @修改记录:
 * @版本: 1.0
 */
@Slf4j
@ServerEndpoint(value = "/ws/warning")
@Component
public class WarningWebsocket {

	private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

	// 发送消息
	public void sendMessage(Session session, String message) throws IOException {
		if (session != null) {
			synchronized (session) {
//                System.out.println("发送数据：" + message);
				session.getBasicRemote().sendText(message);
			}
		}
	}

	// 给指定用户发送信息
	public void sendInfo(String message) {
		log.info("发送消息：" + message);
		sessionPools.values().forEach(session -> {
			try {
				sendMessage(session, message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

	}

	// 建立连接成功调用
	@OnOpen
	public void onOpen(Session session) {
		sessionPools.put(session.getId(), session);
	}

	// 关闭连接时调用
	@OnClose
	public void onClose(Session session) {
		sessionPools.remove(session.getId());
	}

	// 收到客户端信息
	@OnMessage
	public void onMessage(String message) throws IOException {
		log.error(message);
		for (Session session : sessionPools.values()) {
			try {
				sendMessage(session, message);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}

	// 错误时调用
	@OnError
	public void onError(Session session, Throwable throwable) {
		log.error("发生错误", throwable);
	}

}
